﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Naruto.Subscribe.Interface;
using Naruto.Subscribe.Object;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Naruto.Subscribe.Internal
{
    /// <summary>
    /// 消费者注册
    /// </summary>
    internal class ConsumerRegister : IConsumerRegister
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly IServiceProvider serviceProvider;
        /// <summary>
        /// 
        /// </summary>
        private readonly ILogger logger;
        /// <summary>
        /// 
        /// </summary>
        private readonly SubscribeOption subscribeOption;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_serviceProvider"></param>
        public ConsumerRegister(IServiceProvider _serviceProvider, ILogger<ConsumerRegister> _logger, IOptions<SubscribeOption> _subscribeOption)
        {
            serviceProvider = _serviceProvider;
            logger = _logger;
            subscribeOption = _subscribeOption.Value;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task RegisterAsync(CancellationToken cancellationToken = default)
        {
            //获取所有需要订阅的名称
            var subscribeNames = SubscribeTypeFactory.GetAllSubscribeName();
            logger.LogTrace("当前订阅总数,{count}", subscribeNames?.Count);
            if (subscribeNames != null && subscribeNames.Count() > 0)
            {
                var subscribeEvent = serviceProvider.GetService<IConsumerSubscribe>();
                if (subscribeEvent != null)
                {
                    var tasks = new List<Task>();
                    for (int i = 1; i <= subscribeOption.ConsumerThreadCount; i++)
                    {
                        tasks.Add(Task.Factory.StartNew(async () =>
                       {
                           await subscribeEvent.SubscribeAsync(subscribeNames, cancellationToken).ConfigureAwait(false);
                       }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default));
                    }
                    if (tasks.Count > 0)
                    {
                        await Task.WhenAll(tasks).ConfigureAwait(false);
                    }
                }
                else
                    logger.LogWarning("当前未实现订阅服务");
            }
        }
    }
}
